package com.young.rpc.handler;

import com.google.gson.Gson;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.young.job.JobContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;

/**
 * @description：
 * @author: yangyahui01
 * @date: 11/25/24 3:32 PM
 */

public class DefaultHttpJobCheckHandler implements HttpHandler {

    public static final String APPLICATION_JSON = "application/json; charset=UTF-8";

    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultHttpJobCheckHandler.class);

    private static final Gson GSON = new Gson();

    private final LocalByteArray response = new LocalByteArray();

    private final JobHandler jobHandler;

    public DefaultHttpJobCheckHandler(JobHandler jobHandler) {
        this.jobHandler = jobHandler;
    }


    public void handle(HttpExchange httpExchange) throws IOException {
        JobContext jobContext = context(httpExchange);
        jobHandler.check(jobContext);

        ByteArrayOutputStream response = this.response.get();
        response.reset();
        OutputStreamWriter osw = new OutputStreamWriter(response);
        try {
            osw.flush();
            osw.close();
            response.flush();
            response.close();

            LOGGER.info("handle 已执行");

            httpExchange.getResponseHeaders().set("Content-Type",
                    APPLICATION_JSON);
            httpExchange.getResponseHeaders().set("Content-Length",
                    String.valueOf(response.size()));
            httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.size());
            httpExchange.getResponseBody();
            response.writeTo(httpExchange.getResponseBody());
        } finally {
            httpExchange.close();
        }

    }

    private JobContext context(HttpExchange httpExchange) {
        BufferedReader bufferedReader = null;
        JobContext jobContext = null;
        StringBuffer stringBuffer = new StringBuffer();
        try {
            bufferedReader = new BufferedReader((new InputStreamReader(httpExchange.getRequestBody())));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line.trim());
            }
            jobContext = GSON.fromJson(stringBuffer.toString(), JobContext.class);
        } catch (Exception e) {
            LOGGER.error("DefaultHttpJobHandler 获取请求参数异常", e);
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                    bufferedReader = null;
                }
            } catch (IOException e) {
                //
            }
        }
        return jobContext;
    }

    private static class LocalByteArray extends ThreadLocal<ByteArrayOutputStream> {
        protected ByteArrayOutputStream initialValue() {
            return new ByteArrayOutputStream(1 << 20);
        }
    }
}
